import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core';

@Directive({
    selector: '[opTextAutoSizeNoWrapDirective]',
})
export class TextAutoSizeNoWrapDirective implements AfterViewInit {
    @Input() containerHeight: number;
    @Input() fontSize: number;

    constructor(private elementRef: ElementRef) { }

    ngAfterViewInit(): void {
        // Why setInterval instead of while loop?
        // The while loop blokcs the rerender in call stack. That causes the infinit loop.
        // setInterval inserts a new task in the queue each time it runs.
        // One task completes with rerender.
        let interval = setInterval(() => {
            if (this.elementRef.nativeElement.clientHeight > this.containerHeight) {
                this.fontSize--;
                this.elementRef.nativeElement.style.fontSize = `${this.fontSize}px`;
            } else {
                clearInterval(interval);
                interval = null;
            }
        }, 0);
    }
}